package main.java.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumer03 {
    public static void main(String[] args) {
        long nanoTime = System.nanoTime();
        date3 date3 = new date3();
        new Thread(()->{
            for (int i = 0;i<1000;i++){
                date3.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0;i<1000;i++){
                date3.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0;i<1000;i++){
                date3.printC();
            }
        },"C").start();
        while(Thread.activeCount() >= 3){
            Thread.yield();
        }
        System.out.println(System.nanoTime() - nanoTime);
    }
}

class date3 {
    private int num = 1;
    Lock lock = new ReentrantLock();

    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    public void printA(){
        lock.lock();
        try {
            while (num!=1){
                conditionA.await();
            }
            num = 2;
            System.out.println(Thread.currentThread().getName()+"->A");
            conditionB.signal();
//            conditionA.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printB(){
        lock.lock();
        try {
            while(num != 2){
                conditionB.await();
//                conditionA.await();
            }
            num = 3;
            System.out.println(Thread.currentThread().getName()+"->B");
            conditionC.signal();
//            conditionA.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printC(){
        lock.lock();
        try {
            while(num != 3){
                conditionC.await();
//                conditionA.await();
            }
            num = 1;
            System.out.println(Thread.currentThread().getName()+"->C");
            conditionA.signal();
//            conditionA.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
